/*
 * cow.c
 *
 *  Created on: May 26, 2014
 *      Author: eran
 */

#include "types.h"
#include "stat.h"
#include "user.h"


int
main(int argc, char *argv[])
{
	int *num1 = malloc(sizeof(int));
	char* p;
	int pid0;
	int pid1;
	int pid2;
	int i;
	p = (char*)main;
	pid0 = fork();
	if (pid0)
		printf(1, "PID%d created with fork, and is going to sleep for a while. Type ^P.\n", pid0);
	sleep(1000);
	if (!pid0){
		printf(1, "PID%d will try and access virtual address 0.\n", getpid());
		*((int*)pid0) = 5;
		printf(1, "oops...\n");
		exit();
	}
	pid0 = fork();
	if (pid0)
		printf(1, "PID%d created with fork, and is going to sleep for a while.\n", pid0);
	sleep(1000);
	if (!pid0){
		printf(1, "PID%d will try and access main address 0.\n", getpid());
		p[0] = 'f';
		printf(1, "oops...\n");
		exit();
	}
	sleep(1000);
	pid1= cowfork();
	if (pid1)
		pid2 = cowfork();
	if (pid2)
		printf(1, "PID%d & PID%d created with cowfork, and are going to sleep for a while. Type ^P.\n", pid1, pid2);
	sleep(1000);
	if (pid1 && !pid2){
		*num1 = 5;
		printf(1, "PID%d changed num, and is going to sleep for a while. Type ^P.\n", getpid());
	}
	sleep(1000);
	if(pid1 && pid2){
		*num1=6;
		printf(1, "PID%d changed num, and is going to sleep for a while. Type ^P.\n", getpid());
	}
	sleep(1000);
	if(!pid1 && !pid2){
		*num1=6;
		printf(1, "PID%d changed num, and is going to sleep for a while. Type ^P.\n", getpid());
	}
	sleep(1000);
	if(pid1 && pid2){
		for(i = 0; i<4; i++)
			wait();
	}

	exit();

}
